import { defineStore } from "pinia";
import axios from "axios";
import { reactive } from "vue";

const useQuestionStore = defineStore('question', () => {
  const state = reactive({
    questionList: [],   // 存放题目
    answerList: [],   // 答案 
    num: 0  
  })

// 仓库中的变量想要修改值，一定要用仓库中定义的函数
  function getQuestionList() {// 修改
    // 获取题目
    axios.get('https://mock.mengxuegu.com/mock/6767738f98077b17fe6792e2/question-naire')
      .then(res => {
        console.log(res);
        state.questionList = res.data.questions        
      })
  }

  //获取用户选择的答案
  function saveAnswerList(answer) {
    state.answerList.push(answer)
  }

  //跳转题目
  function addNum() {
    state.num++
  }

  //获取总分
  function getScore() {
    let num = 0
    for (let i = 0; i < state.questionList.length; i++) {
      for (let j = 0; j < state.questionList[i].topic_answer.length; j++) {
        if (state.questionList[i].topic_answer[j].topic_answer_id === state.answerList[i]
          && state.questionList[i].topic_answer[j].is_standard_answer
        ) num++
      }      
    }
    
    return num / state.questionList.length * 100
  }

  return {
    state,
    getQuestionList,
    saveAnswerList,
    addNum,
    getScore
  }
})

export default useQuestionStore